package org.ko.core.dao.hibernate4;

import java.lang.annotation.Annotation;
import java.lang.reflect.Field;
import java.util.HashMap;
import java.util.Map;

import javax.persistence.Table;

import org.ko.commons.config.PropertyConfigurer;

/**
 * 提供了获取真实数据表名的一系列方法
 * 
 * @author zengxm 2014-9-25
 */
public final class TableHelper {
	private static Map<String, String> tableMap = new HashMap<String, String>();
	private static String table_pre = null;
	/**
	 * <pre>
	 *根据实体类名获取真实数据库中的表明
	 *</pre>
	 * @param cls
	 * @return
	 */
	@SuppressWarnings("rawtypes")
	public static String getTableName(final Class cls){
		String clsName = cls.getName();
		if(tableMap.containsKey(clsName))
			return tableMap.get(clsName);
		
		Field[] fields = cls.getDeclaredFields();
		fields[0].getAnnotation(Table.class);
		
		Annotation[] annos = cls.getDeclaredAnnotations();
		for(int i=0;i<annos.length;i++){
			String annoType = annos[i].annotationType().toString();
			if(annoType.endsWith(Table.class.getName())){
				Table tab = (Table)annos[i];
				
				String tableName = getTablePre()+tab.name();
				tableMap.put(clsName, tableName);
				System.out.println("缓存表名[key="+clsName+", tableName="+tableName+"]");
				return tableName;
			}
		}
		return "";
	}
	
	private static String getTablePre(){
		if(table_pre==null)
			table_pre = PropertyConfigurer.getProperty("hibernate.table_prefix");
		if(table_pre != null){
			table_pre+=(table_pre.indexOf("_")>-1)?"":"_";
		}else
			table_pre = "";
		return table_pre;
	}
	
}